package com.kumarn.android.imagesave.full;

import java.io.File;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

import com.kumarn.android.imagesave.full.adapter.GoodsListAdapter;
import com.kumarn.android.imagesave.full.adapter.GoodsListItem;
import com.kumarn.android.imagesave.full.db.DBOpenHelper;
import com.kumarn.android.imagesave.full.manager.DirectoryManager;
import com.kumarn.android.imagesave.full.manager.StorageManager;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;

public class GoodsListActivity extends Activity {

	private static final int MENU_ADD = 0x7f999900;
	List<GoodsListItem> items;

	/**
	 * リストをセット
	 */
	private void setList(){
		//DBアクセス
		DBOpenHelper dbHelper = new DBOpenHelper(this);
		SQLiteDatabase db = dbHelper.getWritableDatabase();

		//グッズのリストを取得
		String SELECT_T_CONTENT = "SELECT goods_id,goods_image,goods_name, goods_memo,goods_group_name FROM t_goods LEFT JOIN t_goods_group ON goods_group = goods_group_id ORDER BY goods_id;";
		Cursor cursol = db.rawQuery(SELECT_T_CONTENT, null);

		items = new ArrayList<GoodsListItem>();
		while (cursol.moveToNext()) {

			Bitmap bmp = null;

			//ファイル存在確認
			String filepath = (new DirectoryManager()).getImageDir().getPath() + "/" + cursol.getString(1);
			File file = new File(filepath);

			//ファイルがあれば取得
			if(file.exists()){
				//画像保存PathからBitmap取得
				bmp = BitmapFactory.decodeFile(filepath);
			//無ければnoImage画像をセット
			}else{
				Resources res = this.getResources();
				bmp = BitmapFactory.decodeResource(res, R.drawable.noimage);
			}

			//メモの改行を半角スペースに変換
			String memo = cursol.getString(3);
			memo = memo.replace("\n", " ");

			String groupName = cursol.getString(4);
			if(groupName != null && groupName.length() > 0){
				groupName = "[" + groupName + "]";
			}


			//一行ごとにリストを登録
			items.add(new GoodsListItem(cursol.getInt(0),cursol.getString(2), memo,bmp,groupName));
		}
		cursol.close();
		db.close();

		//アダプタセット
		GoodsListAdapter adapter = new GoodsListAdapter(this,R.layout.goods_row, items);

		ListView list = (ListView) findViewById(R.id.goodsListview);
		list.setAdapter(adapter);
		list.setOnItemClickListener(new OnClickEvent());
		list.setOnItemLongClickListener(new OnLongClickEvent());
	}

	/**
	 * リストクリック
	 * @author kuma
	 *
	 */
	class OnClickEvent implements OnItemClickListener {

    public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
    	GoodsListItem gli = items.get(position);
			int gid = gli.getList_goods_id();

			Intent i = new Intent(getApplicationContext(),GoodsAddActivity.class);
			i.putExtra("METHOD", "edit");
			i.putExtra("ID",gid);
			startActivity(i);
		}
	}

	/**
	 * リストロングクリック
	 * @author kuma
	 *
	 */
	class OnLongClickEvent implements OnItemLongClickListener {

		public boolean onItemLongClick(AdapterView<?> adapter, View view, int position, long id) {

			GoodsListItem gli = items.get(position);
			final int gid = gli.getList_goods_id();		//グッズID
			final String gName = gli.getList_goods_name();	//グッズ名

			final CharSequence[] menu = { "編集", "削除" };
			new AlertDialog.Builder(GoodsListActivity.this)
				.setTitle(gName)
				.setItems(menu, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						//編集選択
						if (item == 0) {
							Intent i = new Intent(getApplicationContext(),GoodsAddActivity.class);
							i.putExtra("METHOD", "edit");
							i.putExtra("ID", gid);
							startActivity(i);
						//削除選択
						} else if (item == 1) {
							new AlertDialog.Builder(GoodsListActivity.this)
								.setTitle(gName)
								.setMessage("削除しますか？")
								.setPositiveButton("削除", new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int whichButton) {
										DBOpenHelper dbHelper = new DBOpenHelper(GoodsListActivity.this);
										SQLiteDatabase db = dbHelper.getWritableDatabase();

										db.execSQL("DELETE FROM t_goods WHERE goods_id ="+gid);
										db.close();
										setList();
										dialog.cancel();
									}
								})
								.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int whichButton) {

									}
								}).show();
						}
					}
				}).show();

			return false;
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.goods_list);

		StorageManager sm = new StorageManager();
		String result = sm.strageCheck(this);
		if(!result.equals("ok")){
			new AlertDialog.Builder(this)
				.setTitle("SDカードエラー")
				.setMessage(result + "\n\nアプリケーションを終了します")
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
						finish();
					}
				}).show();
		}else{
			setList();

		}
		Log.d("", result);


	}

	@Override
	public void onRestart(){
		super.onRestart();
		setContentView(R.layout.goods_list);
		setList();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// 新規登録
		menu.add(Menu.NONE, MENU_ADD, Menu.NONE, R.string.new_add).setIcon(
				android.R.drawable.ic_menu_add);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		boolean ret = true;
		switch (item.getItemId()) {
		default:
			ret = super.onOptionsItemSelected(item);
			break;
		case MENU_ADD:
			// 新規登録ボタンが押された時
			Intent i = new Intent(GoodsListActivity.this,GoodsAddActivity.class);
			i.putExtra("METHOD", "add");
			startActivity(i);
			break;
		}

		return ret;
	}
}